package com.woniuxy.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:ABA问题
 * <P> Date: 2022/4/9:12:49
 * <P> Description:
 */
@Slf4j(topic = "c.ABAQuestion02")
@SuppressWarnings("all")
public class ABAQuestion02 extends Thread {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);

    public static void main(String[] args) throws InterruptedException {
        log.debug("main start...");
        // 获取值 A
        // 这个共享变量被它线程修改过？
        String prev = ref.getReference();
        //TODO 获取版本号
        int stamp = ref.getStamp();
        other();

        sleep(1000);
        log.debug("版本号：{}", stamp);
        // 尝试改为 C
        log.debug("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));
    }

    private static void other() throws InterruptedException {
        new Thread(() -> {
            //TODO 获取版本号
            int stamp = ref.getStamp();
            log.debug("版本号：{}", stamp);
            log.debug("change A->B {}", ref.compareAndSet(ref.getReference(),
                    "B",
                    stamp,
                    stamp + 1));
        }, "t1").start();
        sleep(500);
        new Thread(() -> {
            //TODO 获取版本号
            int stamp = ref.getStamp();
            log.debug("版本号：{}", stamp);
            log.debug("change B->A {}", ref.compareAndSet(ref.getReference(),
                    "B",
                    stamp,
                    stamp + 1));
        }, "t2").start();
    }
}
